package HashPackage2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Lzm
 * @version 1.0
 */
public class fourSum_ {
  public static void main(String[] args) {
    int[] nums = new int[]{1000000000,1000000000,1000000000,1000000000};
    int target = -294967296;
    List<List<Integer>> lists = fourSum(nums, target);
    for (List<Integer> list : lists) {
      for (Integer integer : list) {
        System.out.println(integer);
      }
    }
  }

  public static List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> result = new ArrayList<>();
    // 1. 排序
    Arrays.sort(nums);
    if (nums[0] > target){
      return result;
    }
    if (nums.length == 4 && (nums[0] + nums[1] + nums[2] + nums[3]) != target){
      return result;
    }
    for (int i = 0; i < nums.length; i++) {
      if (i > 0 && nums[i] == nums[i - 1]){
        continue;
      }
      for (int k = i + 1 ; k < nums.length ; k++){
        if (k > i + 1 && nums[k] == nums[k - 1]){
          continue;
        }
        int left = k + 1;
        int right = nums.length - 1;
        while(left < right){
          long sum = nums[i] + nums[k] + nums[left] + nums[right];
          if (sum > target){
            right--;
          }
          else if (sum < target){
            left++;
          }
          else if (sum == target){
            List<Integer> list = new ArrayList<>();
            list.add(nums[i]);
            list.add(nums[k]);
            list.add(nums[left]);
            list.add(nums[right]);
            result.add(list);
            while(left < right && nums[left] == nums[left + 1]){
              left++;
            }
            while(left < right && nums[right] == nums[right + 1]){
              right--;
            }
            left++;
            right--;
          }
        }
      }
    }
    return result;
  }
}
